package com.mdc.mansion.api.web.modules.system.web.qrCode;

import com.mdc.mansion.api.web.common.interceptor.NoLoginCheck;
import com.mdc.mansion.api.web.common.web.BaseController;
import com.mdc.mansion.common.exception.BusinessException;
import com.mdc.mansion.common.response.Result;
import com.mdc.mansion.common.response.ResultCode;
import com.mdc.mansion.common.util.I18nUtil;
import com.mdc.mansion.core.modules.basedata.dto.AppConfigDTO;
import com.mdc.mansion.core.modules.restaurant.RestaurantTableService;
import com.mdc.mansion.core.modules.system.SysDictService;
import com.mdc.mansion.dataaccess.modules.restaurant.entity.RestaurantTable;
import com.mdc.mansion.dataaccess.modules.system.entity.Dict;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

import static com.mdc.mansion.core.modules.basedata.dto.AppConfigDTO.qrCodeRedirectUrl;

@RequestMapping("${adminPath}/getQrCode")
@Controller
public class QrCodeController extends BaseController {

    @Resource
    private RestaurantTableService restaurantTableService;

    @Resource
    private SysDictService sysDictService;

    @NoLoginCheck
    @RequestMapping
    public String getQrCode(String codeSign){
        RestaurantTable restaurantTable=new RestaurantTable();
        restaurantTable.setQrCodeSign(codeSign);
        List<RestaurantTable> restaurantTables = restaurantTableService.findList(restaurantTable);
        if(CollectionUtils.isEmpty(restaurantTables)){
            Dict dict = new Dict();
            dict.setType(AppConfigDTO.qrCodeBotBindUrl);
            List<Dict> list = sysDictService.findList(dict);
            String qrCodeBotBindUrl=list.get(0).getValue();
            return "redirect:"+qrCodeBotBindUrl;
        }
        Dict dict = new Dict();
        dict.setType(qrCodeRedirectUrl);
        List<Dict> list = sysDictService.findList(dict);
        String qrCodeRedirectUrl=list.get(0).getValue();
        return "redirect:"+qrCodeRedirectUrl+"?tableid="+restaurantTables.get(0).getId()+"&restaurantId="+restaurantTables.get(0).getRestaurantId();
    }

    @NoLoginCheck
    @RequestMapping("getTableIdByQrCode")
    public Result getTableIdByQrCode(String codeSign){
        RestaurantTable restaurantTable=new RestaurantTable();
        restaurantTable.setQrCodeSign(codeSign);
        List<RestaurantTable> restaurantTables = restaurantTableService.findList(restaurantTable);
        if(CollectionUtils.isEmpty(restaurantTables)){throw new BusinessException(I18nUtil.getMessage("qrcode.not.bind"));}
        Result result=new Result(ResultCode.COMMON_SUCCESS);
        result.setProperty("tableId",restaurantTables.get(0).getId());
        return result;
    }
}
